using System;
using System.Reflection;
using NHibernate;
using NHibernate.Property;

namespace Technoera.Common.Nh.CustomPropertyAccessors
{
    public sealed class DateGetter : IGetter
    {
        private Type classType;
        private PropertyInfo property;
        private string propertyName;

        public DateGetter(Type classType, PropertyInfo property, string propertyName)
        {
            this.classType = classType;
            this.property = property;
            this.propertyName = propertyName;
        }

        #region IGetter Members

        public object Get(object target)
        {
            try
            {
                object propertyValue = property.GetValue(target, new object[0]);
                if (propertyValue is DateTime && (DateTime)propertyValue == DateTime.MinValue)
                {
                    return null;
                }
                else
                {
                    return propertyValue;
                }
            }
            catch (Exception e)
            {
                throw new PropertyAccessException(e, "Exception occurred", false, classType, propertyName);
            }
        }

        public Type ReturnType
        {
            get { return property.PropertyType; }
        }

        public string PropertyName
        {
            get { return property.Name; }
        }

        public PropertyInfo Property
        {
            get { return property; }
        }

        /// <summary>
        /// Gets the <see cref="PropertyInfo"/> for the mapped Property.
        /// </summary>
        /// <value>The <see cref="PropertyInfo"/> for the mapped Property.</value>
        public MethodInfo Method
        {
            get { return property.GetSetMethod(true); }
        }

        #endregion
    }
}
